﻿//Copyright (C) <2013>  <jonathan cleeve norton> All Rights Reserved 
//Contact jon.norton@fin-plus.co.uk website <http://www.fin-plus.co.uk/>
using System;
using FinPlusInterfaces;

namespace FinPlusAssembler
{
    public static class FinPlusCmdInject
    {
        //public
        public static void CmdsExecute(this IPod pod, IPods commands)
        {
            try
            {
                foreach (var evnt in commands.Values)
                    InjectCommand(pod, evnt);
            }
            catch 
            {
                return;
            }
        }

        //private
        private static void InjectCommand(this IPod pod, IPod command)
        {
            var model = pod.Property("Adapter");
            if (model == null) return;

            foreach (var child in ((IPods)model).Values)
            {
                var childId = child.Property(PodField.Id.ToString());
                if (childId != null && childId.ToString() == command[PodField.Id.ToString()].ToString())
                    child.InvokeCmdExecute(command);
                else
                    child.InjectCommand(command);
            }
        }

        private static void InvokeCmdExecute(this IPod pod, IPod command)
        {
            try
            {
                var methodInfo = pod.Object.GetType().GetMethod("CmdExecute");
                var parms = new object[] { command };
                object res = methodInfo.Invoke(pod.Object, parms);
            }
            catch (Exception e)
            {
                command.Object = e;
            }
        }
    }
}
